import { defineComponent, reactive } from 'vue';
import './FighterPopup.less';
import { Popup, Icon } from 'vant';
import { find } from 'lodash-es';
import { useVModels } from '@vueuse/core';
import { CardListApi } from '/@/api/verse/card';
import { awaitWrap } from '/@/utils';
import { CardType } from '/@/api/verse/model/cardModel';
import type { CardList } from '/@/api/verse/model/cardModel';
import type { DeckCardItem } from '/@/api/verse/model/deckModel';
import { useVerseStore } from '/@/store/modules/verse';

export default defineComponent({
  name: 'FighterPopup',
  props: {
    show: {
      type: Boolean as PropType<boolean>,
      required: true,
      default: () => {
        return false;
      },
    },
  },
  setup(props, { emit }) {
    const { show } = useVModels(props, emit);

    const verseStore = useVerseStore();

    const fighterList = reactive<DeckCardItem[]>([]);

    const getFighterList = async () => {
      const [error, data] = await awaitWrap(
        CardListApi({ page: 1, page_size: 50, card_type: CardType.WARRIOR }, 'none')
      );
      if (error) {
        return;
      }
      const result = data as CardList;
      for (const item of result.rows) {
        fighterList.push(item);
      }
    };
    getFighterList();

    const addFighter = (card: DeckCardItem) => {
      verseStore.setCreateDeckFighter(card);
    };

    return () => (
      <Popup v-model={[show.value, 'show']} class={'fighter-card-popup'} teleport={'body'} round={true} closeable>
        <h3 class={'fighter-title'}>选择主战者</h3>
        <ul class={'fighter-list flex flex-wrap'}>
          {fighterList.map((item) => {
            let active = '';
            let IconActive: any = <span></span>;
            const target = find(verseStore.getCreateDeckParams.main_fighters, ['card_id', item.card_id]);
            if (target) {
              active = 'active';
              IconActive = <Icon name={'checked'} />;
            }
            return (
              <li
                class={`fighter-item ${active}`}
                onClick={() => {
                  addFighter(item);
                }}
              >
                <IconActive />
                <img src={item.img} alt='' />
              </li>
            );
          })}
        </ul>
      </Popup>
    );
  },
});
